package com.lwq.nacos.grayscale.filter;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.lwq.nacos.grayscale.constants.Constants;
import com.lwq.nacos.grayscale.gray.NacosMetaDataContext;
import com.lwq.nacos.grayscale.gray.NacosMetaDataContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.security.Principal;
import java.util.List;

/**
 * 针对spring cloud gateway做灰度处理
 */
@Configuration
@Slf4j
public class WebFluxFilter implements WebFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        ServerHttpRequest request = serverWebExchange.getRequest();
        List<String> grayNameList = request.getHeaders().get(Constants.GRAY_HEADER_NAME);
        NacosMetaDataContext context = NacosMetaDataContextHolder.getContext();
        if (CollectionUtil.isNotEmpty(grayNameList)){
            String grayName = grayNameList.get(0);
            if (StrUtil.isNotBlank(grayName)){
                context.put(Constants.GRAY_HEADER_NAME,grayName);
            }
        }
        return webFilterChain.filter(serverWebExchange).doFinally((onFinally) ->{
            log.info("webflux finally before remove finally={}, jsonContext={}", context, context);
            context.clear();
            log.info("webflux finally after remove finally={}, jsonContext={}", context, context);
        });
    }


    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }


}
